<template>
  <div class="configTable">
    <configCompositionTwoWindowStyle :leftWidth="16" :rightWidth="8" :height="100">
      <template slot="card">
        <div style="margin-right: 20px;" class="webChatUrlTable">
          <diyTable :currentPageData="currentPage" :tableHeader="currentTableHeader" :tableData="tableData" :isShow="isShow" :countTotal="countNum" v-loading="refreshLoading" @updata="updata" @del="del" @add="add" @refresh="refresh" @turnPage="turnPage">
            <template slot="column">
              <template v-for="(item, index) in currentTableHeader">
                <el-table-column v-if="item.prop === 'switch'" :key="index" :prop="item.prop" :label="item.label">
                  <template slot-scope="scope">
                    <el-switch
                      @change="switchChange($event, scope.row)"
                      v-model="scope.row.switch"
                      active-color="#459ae9"
                      inactive-color="#ccc">
                    </el-switch>
                  </template>
                </el-table-column>
              </template>
            </template>
          </diyTable>
        </div>
      </template>
      <template slot="detail">
        <div v-if="isShowDetail">
          <breadCrumb :titleArr="titleArr" @back="back"></breadCrumb>
          <div class="webChatUrlDetail" v-if="activeName === 'application'">
            <div class="webChatUrl_from">
              <el-form :model="applicatForm" ref="applicatForm" :rules="applicatFormRules" label-position="top" label-width="120px">
                <el-form-item label="类型" prop="application">
                  <el-select v-model="applicatForm.category" filterable placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="(item, index) in detailData.categories"
                      :key="index"
                      :label="item.name"
                      :value="item.category">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                  <el-input :maxlength="20" v-model.trim="applicatForm.name" :placeholder="$t('configLazyLoad.robotSeven.pleaseInput')"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="url">
                  <el-input v-model.trim="applicatForm.url" :placeholder="$t('configLazyLoad.robotSeven.pleaseInput')"></el-input>
                </el-form-item>
                <el-form-item label="菜单栏展示顺序" prop="order">
                  <el-select v-model="applicatForm.order" filterable placeholder="请选择" style="width: 100%">
                    <el-option
                      v-for="(item, index) in orderOption"
                      :key="index"
                      :label="item.name"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="图标" prop="icon" v-if="applicatForm.category === 'app'">
                  <el-radio-group v-model="applicatForm.icon">
                    <el-radio v-for="(item, index) in iconArr" :label="item" :key="index"><i :class="'iconfont ' + item"></i></el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" class="primary_btn" @click="submitForm('applicatForm')">保存</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="webChatUrlDetail" v-else>
            <div class="webChatUrl_from">
              <el-form :model="detailFormData" ref="detailForm" :rules="rules" label-position="top" label-width="120px">
                <el-form-item v-for="(item, index) in detailData" :label="item.label" :prop="item.prop" :key="index">
                  <el-input :maxlength="item.prop === 'name' ? 20 : ''" v-model.trim="detailFormData[item.prop]" :placeholder="$t('configLazyLoad.robotSeven.pleaseInput')"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" class="primary_btn" @click="submitForm('detailForm')">保存</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </template>
    </configCompositionTwoWindowStyle>
  </div>
</template>

<script>
  import diyTable from '../interfaceConfig/base/diyTable'
  import breadCrumb from '../../../ui-modules/breadCrumb/BreadCrumbConfig.vue'
  import configCompositionTwoWindowStyle from '../../../ui-modules/config/configCompositionTwoWindowStyle'
  import { deepClone } from "../../../../utils/m7Utils";
  export default {
    name: 'ConfigTable',
    data () {
      return {
        tableData: [],
        isShowDetail: false,
        isShow: true,
        titleArr: [],
        detailFormData: {
          name: '',
          accessKey: 'http://',
          secretKey: '',
          yunmiId: ''
        },
        applicatForm: {
          category: 'app',
          name: '',
          url: 'http://',
          icon: 'icon-xiangmuguanli',
          order: ''
        },
        iconArr: [
          'icon-xiangmuguanli',
          'icon-CSM',
          'icon-kehugonghai',
          'icon-tonghua1',
          'icon-BIbaobiao',
          'icon-hangzhengguanli',
          'icon-caiwuguanli',
          'icon-zhanghuguanli',
          'icon-zhishiku',
          'icon-youjian2',
          'icon-bugguanli',
          'icon-jiankong',
          'icon-HRM',
          'icon-AI',
          'icon-gongdan2',
          'icon-EPR',
          'icon-OA',
          'icon-dingdanguanli',
          'icon-CRM'
        ],
        applicatFormRules: {
          categorie: [{required: true, message: '请选择类型', trigger: 'change'}],
          name: [{required: true, message: '请输入名称', trigger: 'blur'}],
          url: [
            {required: true, message: '请输入正确的地址', trigger: 'blur'},
            {pattern: /^((http|ftp|https):\/\/)(([a-zA-Z0-9._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,4})*(\/[a-zA-Z0-9&%_./-~-]*)?/,
              message: '请输入正确的地址' }
          ],
          order: [{required: true, message: '请选择顺序', trigger: 'change'}],
        },
        refreshLoading: false,
        addOrEdit: 'add',
        webChatId: '',
        countNum: 0,
        currentPage: 1,
        pageSize: 10
      }
    },
    mounted () {
      this.getDiDiList(1)
    },
    computed: {
      currentTableHeader () {
        let currentData = deepClone(this.configData).filter(item => {return item.robottype === this.activeName})
        currentData[0].value.push({prop: 'operate', label: this.$t('public.operate')})
        currentData[0].value.forEach(item => {
          if (item.prop === 'enabled') {
            item.prop = 'switch'
          }
        })
        return currentData[0].value
      },
      detailData () {
        let currentData = deepClone(this.configData).filter(item => {return item.robottype === this.activeName})
        if (this.activeName === 'application') {
          return currentData[0]
        } else {
          return currentData[0].value
        }
      },
      titleName () {
        let currentData = deepClone(this.configData).filter(item => {return item.robottype === this.activeName})
        let robotName = currentData[0].robot.split(this.$t('public.robot'))[0]
        return robotName
      },
      rules () {
        let rules = {}
        this.detailData.forEach(item => {
          rules[item.prop] = [{required: true, message: this.$t('public.pleaseInput') + item.label+ this.$t('customer.customerSlot.name'), trigger: 'blur'}]})
        return rules
      }
    },
    props: {
      configData: {
        type: Array,
        default: function () {
          return []
        }
      },
      activeName: {type: String, default: 'yunmi'}
    },
    watch: {
      activeName () {
        this.refresh()
        let obj = {}
        if (this.activeName !== 'application') {
          this.detailData.forEach(item => {
            obj[item.prop] = ''
          })
          this.detailFormData = obj
        }
      }
    },
    methods: {
      switchChange (event, row) {
        let data = JSON.parse(JSON.stringify(row))
        data.enabled = event
        delete data.switch
        this.$store.dispatch('updateThirdAppConfig', data).then(res => {
          if (res && res.success) {
            this.getDiDiList(this.currentPage)
            this.isShowDetail = false
            this.$message.success('变更状态成功')
          }
        })
      },
      getDiDiList (val) {
        this.$store.dispatch('getListByAppType', {limit: 10, page: val, type: this.activeName}).then(res => {
          if (res.success) {
            this.countNum = res.count
            this.tableData = res.data
            this.tableData.forEach(item => {
              item.switch = item.enabled
            })
            let arr = []
            if (this.countNum > 0) {
              for (let i = 0; i < this.countNum + 1; i++) {
                arr.push({name: i + 1, value: i + 1})
              }
            } else {
              arr = [{name: 1, value: 1}]
            }
            this.orderOption = arr
          }
          this.refreshLoading = false
        })
      },
      back () {
        this.isShowDetail = false
      },
      add () {
        this.titleArr = [this.titleName + this.$t('configLazyLoad.roleSetting.accountManagement'), this.$t('public.add') + this.titleName + this.$t('login.account')]
        this.addOrEdit = 'add'
        for (var i in this.detailFormData) {
          this.detailFormData[i] = ''
        }
        for (var i in this.applicatForm) {
          this.applicatForm[i] = ''
        }
        this.applicatForm.category = 'app'
        this.applicatForm.icon = 'icon-xiangmuguanli'
        this.applicatForm.url = 'http://'
        this.isShowDetail = true
      },
      updata (val) {
        this.titleArr = [this.titleName + this.$t('configLazyLoad.roleSetting.accountManagement'), this.$t('public.edit2') + this.titleName + this.$t('login.account')]
        this.addOrEdit = 'edit'
        this.webChatId = val._id
        this.isShowDetail = true
        for (var i in this.detailFormData) {
          this.detailFormData[i] = val[i]
        }
        for (var i in this.applicatForm) {
          this.applicatForm[i] = val[i]
        }
        this.pageSize = 10
      },
      del (val) {
        let data = {}
        data._id = val._id
        this.$confirm(this.$t('configLazyLoad.roleSetting.confirmDelete'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('deleteThirdAppConfig', {_id: data._id}).then(res => {
            if (res && res.success) {
              this.currentPage = 1
              this.getDiDiList(this.currentPage)
              this.$message({
                message: this.$t('configLazyLoad.roleSetting.successDelete'),
                type: 'success'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('public.cancel')
          })
        })
      },
      turnPage (val) {
        this.currentPage = val
        this.getDiDiList(val)
      },
      submitForm (val) {
        this.$refs[val].validate((valid) => {
          if (valid) {
            let data  = {
              appType: 'robot',
              type: this.activeName
            }
            if (this.activeName === 'application') {
              data.appType = 'app'
              data = {...data, ...this.applicatForm}
            } else {
              this.detailData.forEach(item => {
                data[item.prop] = this.detailFormData[item.prop]
              })
            }
            if (this.addOrEdit === 'add') {
              this.$store.dispatch('addThirdAppConfig', data).then(res => {
                if (res && res.success) {
                  this.getDiDiList(this.currentPage)
                  this.isShowDetail = false
                  this.$message.success(this.$t('config.channel.saveSuccess'))
                }
              })
            } else {
              data._id = this.webChatId
              this.$store.dispatch('updateThirdAppConfig', data).then(res => {
                if (res && res.success) {
                  this.getDiDiList(this.currentPage)
                  this.isShowDetail = false
                  this.$message.success(this.$t('config.channel.saveSuccess'))
                }
              })
            }
          } else {
            return false
          }
        })
      },
      refresh () {
        this.currentPage = 1
        this.refreshLoading = true
        this.isShowDetail = false
        this.getDiDiList(this.currentPage)
      }
    },
    components: {
      configCompositionTwoWindowStyle,
      diyTable,
      breadCrumb
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .configTable
    width 300px
  .webChatUrlTable
    overflow-y: auto
    overflow-x: hidden
    width: 100%
    height: calc(100% - 36px)
  .webChatUrlDetail
    width 250px
  .webChatUrl_from
    padding 20px
    .el-input,.el-select
      max-width 220px
  .item
    margin-bottom 20px
</style>
<style lang="stylus">
  .configTable
    .el-radio
      margin 10px 20px 10px 0px
</style>
